<?php
namespace plug;

use Firebase\JWT\JWT as JWTUtil;
use think\facade\Config;

class SUtil
{

	/**
	 * 获取IP
	 */
	static function getIP($long = false)
	{
		$cip = getenv('HTTP_CLIENT_IP');
		$xip = getenv('HTTP_X_FORWARDED_FOR');
		$rip = getenv('REMOTE_ADDR');
		$srip = @$_SERVER['REMOTE_ADDR'];
		if ($cip && strcasecmp($cip, 'unknown')) {
			$ip = $cip;
		} elseif ($xip && strcasecmp($xip, 'unknown')) {
			$ip = $xip;
		} elseif ($rip && strcasecmp($rip, 'unknown')) {
			$ip = $rip;
		} elseif ($srip && strcasecmp($srip, 'unknown')) {
			$ip = $srip;
		}
		preg_match("/[\d\.]{7,15}/", $ip, $match);
		$ip = $match[0] ? $match[0] : 'unknown';
		if ($long) {
			return sprintf("%u", ip2long($ip));
		}
		return $ip;
	}

	/**
	 * 产生随机数
	 * @param $length 产生随机数长度
	 * @param $type 返回字符串类型
	 * @param $hash  是否由前缀，默认为空. 如:$hash = 'zz-'  结果zz-823klis
	 * @return 随机字符串 $type = 0：数字+字母
	 * $type = 1：数字
	 * $type = 2：字符
	 */
	public static function random($length = 32, $type = 0, $hash = '')
	{
		if ($type == 0) {
			$chars = '23456789abcdefghijkmnpqrstuvwxyz';
		} else if ($type == 1) {
			$chars = '0123456789';
		} else if ($type == 2) {
			$chars = 'abcdefghijklmnopqrstuvwxyz';
		}
		$max = strlen($chars) - 1;
		mt_srand(( double )microtime() * 1000000);
		for ($i = 0; $i < $length; $i++) {
			$hash .= $chars [mt_rand(0, $max)];
		}
		return $hash;
	}

	//密码加密
	public static function getHashBackend($password, $pass_random)
	{
		return md5($password . SConstant::ADMINUSERKEY . $pass_random);
	}

	/**
	 * guid
	 * @return string
	 */
	public static function guid()
	{
		if (function_exists('com_create_guid')) {
			$uuid = com_create_guid();
		} else {
			mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45);// "-"
			$uuid = chr(123)// "{"
				. substr($charid, 0, 8) . $hyphen
				. substr($charid, 8, 4) . $hyphen
				. substr($charid, 12, 4) . $hyphen
				. substr($charid, 16, 4) . $hyphen
				. substr($charid, 20, 12)
				. chr(125);// "}"
		}
		return trim($uuid, "{}");
	}

	/**
	 * 根据json web token设置的规则生成token
	 * &#64;return \think\response\Json
	 */
	public static function createjwt($data)
	{
		$data['exp'] = time()+config::get('token.expire_time'); //token过期时间
		$key = md5(config::get('token.key')); //token的签发密钥，验证token的时候需要用到
		$jwt = JWTUtil::encode($data,$key);
		return $jwt;
	}
}

?>
